﻿using Md.Api.DDD;
using Md.Api.Model.Manage.SysUser.Request;
using Md.Api.Model.Manage.SysUser.Response;
using Md.Dapper.Repositories.Md;
using Md.Redis.Repositories;

namespace Md.Api.Service.Manage.SysUser;
/// <summary>
/// 系统用户登录服务
/// </summary>
public class SysUserLoginService : ApiBase<RequestSysUserLoginModel>
{
    /// <summary>
    /// 系统用户仓储
    /// </summary>
    public SysUserRep sysUserRep { get; set; }
    /// <summary>
    /// redis缓存
    /// </summary>
    public MdRedisService _redisService { get; set; }
    /// <summary>
    /// 执行
    /// </summary>
    protected override void ExecuteMethod()
    {
        if (string.IsNullOrWhiteSpace(Parameter.UserPwd))
        {
            throw new AggregateException("用户密码不能为空");
        }

        var userName = Convert.ToString(Parameter.UserName);
        var userPwd = EncrptyHelp.MD5Pwd(Parameter.UserPwd);

        var user = sysUserRep.Login(userName, userPwd);

        if (user == null)
        {
            throw new AggregateException("用户不存在/密码错误");
        }

        if (user.Status != "0")
        {
            throw new AggregateException("用户已停用");
        }

        if (user.DelFlag != "0")
        {
            throw new AggregateException("用户不存在");
        }

        // uuid需要存缓存，uuid对应用户信息
        var uuid = Guid.NewGuid().ToString();

        var userDict = new Dictionary<string, object>
        {
            { "userId", user.UserId},
            { "uuid", uuid },
            { "platform", 1 }
        };

        _redisService.Instance.Set($"{user.UserId}_{userDict["platform"]}", uuid);

        var token = JwtHelp.SetJwtEncode(userDict, Convert.ToDouble(JsonConfig.JsonRead("MdSettings:TokenExpire")));

        _redisService.Instance.Set($"{user.UserId}Token_{userDict["platform"]}", token);

        var res = new ResponseLoginModel();
        res.token = token;
        res.user = user;

        Result.Data = res;
    }
}

